﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.IO;
using System.Net;
using RestSharp;
using CWB.Web.Configuration;
using CWB.Common.Logging;

namespace CWB.Web.ServerTools
{
    public class EnvInfo
    {
        private readonly static ISysLog log = SysLog.GetLogger(typeof(EnvInfo));

        public static void SendEmailToAdminstratorWhenStartService()
        {
            log.Debug("Star prepare send email");
            //AppConfigManager.SystemSetting.
            RestClient client = new RestClient();
            client.BaseUrl = AppConfigManager.SystemSetting.mailgun_BaseUrl;
            client.Authenticator =
                    new HttpBasicAuthenticator("api",
                                               AppConfigManager.SystemSetting.mailgun_Authenticator);
            RestRequest request = new RestRequest();
            request.AddParameter("domain",
                                 AppConfigManager.SystemSetting.mailgun_domain, ParameterType.UrlSegment);
            request.Resource = "{domain}/messages";
            request.AddParameter("from", AppConfigManager.SystemSetting.mailgun_sendfrom);
            request.AddParameter("to", AppConfigManager.SystemSetting.mailgun_sendto);
            request.AddParameter("subject", "System Star UP.");
            request.AddParameter("text", GetEnvText());
            request.Method = Method.POST;

            IRestResponse rr = client.Execute(request);
            if (rr.ErrorException != null)
            {
                log.Debug(string.Format("Send email failed:{0}", rr.ErrorException.Message));
            }
            else
            {
                log.Debug(string.Format("Send email to:{0}", AppConfigManager.SystemSetting.mailgun_sendto));
            }

        }

        public static string GetEnvText()
        {
            StringBuilder sb = new StringBuilder();

            string path = HttpContext.Current.Server.MapPath("\\");
            sb.Append(string.Format("Server.MapPath = {0}\n\r", path));

            string hostname = Dns.GetHostName();
            sb.Append(string.Format("\n\rService Name = {0}\n\r", hostname));

            sb.Append("\n\rService IP address:\n\r");

            string strIPAddress = string.Empty;
            IPAddress[] ips = null;
            ips = Dns.GetHostAddresses(hostname);
            foreach (IPAddress ipa in ips)
            {
                strIPAddress = ipa.ToString();
                sb.Append(strIPAddress + "\n\r");
            }

            return sb.ToString();
        }
    }

    public class objMailgun
    {
        public string baseUrl;
        public string authenticator;
        public string domain;

        private objMailgun()
        {
        }

        public objMailgun instance()
        {
            return new objMailgun();
        }
    }
}
